{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# VAR模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 原理讲解\n",
    "\n",
    "可以参考公众号：[Stata: VAR (向量自回归) 模型](https://mp.weixin.qq.com/s/OxG-sk1MJUB8HV9V6y6Byw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## matlab 实现\n",
    "\n",
    "### VAR 模型\n",
    "\n",
    "VAR.m\n",
    "```matlab\n",
    "function [beta,resid,cov_mat,AIC] = VAR(Y,X,p)\n",
    "% 注意:只是实现了两变量的VAR模型，思考如何实现任意个变量的VAR\n",
    "% p - 滞后阶数\n",
    "% AIC - 信息准则\n",
    "\n",
    "% 1.估计系数\n",
    "[ADLy,ADLx] = ADLxx(Y,X,p,p);\n",
    "[beta1,~,resid1] = regress(ADLy,ADLx);\n",
    "\n",
    "[ADLy,ADLx] = ADLxx(X,Y,p,p);\n",
    "[beta2,~,resid2] = regress(ADLy,ADLx);\n",
    "\n",
    "beta = [beta1';beta2'];\n",
    "resid = [resid1,resid2];\n",
    "\n",
    "% 2.估计AIC值(eviews调整自由度之后的)\n",
    "T = length(ADLy);\n",
    "cov_mat = resid'*resid/(T-3);\n",
    "AIC = log(det(cov_mat))+2*(2*p+1)*2/T;\n",
    "\n",
    "% % 1.载入数据\n",
    "% data = xlsread('C:\\Users\\Administrator\\Desktop\\hourse.xlsx');\n",
    "% f1 = data(:,2); f2 = data(:,3); e = data(:,6);\n",
    "% \n",
    "% % 2.估计VAR模型\n",
    "% [beta,resid,AIC] = VAR(f1,e,2);\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 脉冲响应函数\n",
    "\n",
    "OIRF1.m\n",
    "```matlab\n",
    "function [beta,IR] = OIRF1(Y,X,num,IMP)\n",
    "\n",
    "% num - 脉冲期数\n",
    "\n",
    "% 1.估计VAR模型参数\n",
    "[beta,~,cov_mat] = VAR(Y,X,1);\n",
    "\n",
    "% 2.脉冲响应函数\n",
    "% 2.1 正交化分解，估计P矩阵\n",
    "P = chol(cov_mat, 'lower');\n",
    "% 2.2 估计IR,s=1期为ADt,s=k，则为A^(k)Dt\n",
    "b = beta(:,2:3);\n",
    "SHOCK = zeros(2,1);\n",
    "if IMP == 1\n",
    "    SHOCK(1,1) = 1; \n",
    "elseif IMP == 2\n",
    "    SHOCK(2,1) = 1; \n",
    "end\n",
    "IR = zeros(num,2);\n",
    "IR(1,:) = b*(P*SHOCK);\n",
    "for s=2:num, IR(s,:) = (b*IR(s-1,:)')'; end\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
